<script lang="ts">
// 部门
export default {
  name: "departmentPage"
};
</script>

<script setup lang="ts">
import { reactive, ref, nextTick, onMounted } from "vue";
import { changeHeight } from "/@/utils/public.mixin";
import {
  // VXETable,
  VxeTableInstance,
  VxeFormPropTypes,
  VxeFormInstance
} from "vxe-table";
import {
  queryDeptListByParam,
  addDepartment,
  updateDepartment,
  // deleteDepartment,
  addOrUpdateDeptMenu,
  queryMenuRoleByRoleId
} from "/@/api/basic/department";
import { queryTeamAll } from "/@/api/basic/team";
import { ElTree } from "element-plus";
import { successMessage, errorMessage } from "/@/utils/message";
import { queryMenutreeNoPermission } from "/@/api/system/permission";
import { useRoute } from "vue-router";
const route = useRoute();
const routeName = route.name as string;
const xTable = ref({} as VxeTableInstance);
const xForm = ref({} as VxeFormInstance);
const table = reactive({
  loading: false,
  tableData: [] as any[],
  tableHeight: 0, //表格高度
  listQuery: {
    bindTeamId: "" as any,
    code: "",
    name: "",
    telphone: ""
  }
});
const findList = () => {
  const data: any = {};
  Object.assign(data, table.listQuery);
  data.storageId =
    table.listQuery.bindTeamId === "" || table.listQuery.bindTeamId == -1
      ? -1
      : table.listQuery.bindTeamId;

  table.loading = true;
  queryDeptListByParam(data)
    .then((res: any) => {
      if (res.code === 0) {
        table.tableData = res.data;
        nextTick(() => xTable.value.setAllTreeExpand(true));
      }
      table.loading = false;
    })
    .catch(() => {
      errorMessage("查询失败");
      table.loading = false;
    });
};
const department = reactive({
  submitLoading: false,
  filterName: "",
  selectRow: null,
  showEdit: false,
  teamData: [] as any[],
  treeConfig: {
    transform: true,
    expandAll: true,
    rowField: "u9Id",
    parentField: "parentId"
  },
  formData: {
    id: -1,
    bindTeamId: "" as any,
    parentId: 0,
    code: "",
    companyId: 1,
    name: "",
    email: "",
    telphone: "",
    vieworder: 100
  },
  formRules: {
    name: [{ required: true, message: "请输入部门名称" }],
    code: [{ required: true, message: "请输入部门编码" }]
  } as VxeFormPropTypes.Rules
});

// 修改
const editEvent = (row: any) => {
  Object.keys(department.formData).forEach(key => {
    department.formData[key] = row[key];
  });
  department.formData.bindTeamId = row.bindTeamId == 0 ? "" : row.bindTeamId;
  department.selectRow = row;
  department.showEdit = true;
};
// // 删除
// const removeEvent = async (row: any) => {
//   const type = await VXETable.modal.confirm("您确定要删除该数据?");
//   if (type === "confirm") {
//     const $table = xTable.value;
//     deleteDepartment(row.id).then((res: any) => {
//       if (res.code === 0) {
//         findList();
//         successMessage("删除成功");
//       } else {
//         errorMessage(res.message);
//       }
//     });
//   }
// };
// // 新增
// const insertEvent = async (row: any) => {
//   department.formData = {
//     id: -1,
//     bindTeamId: "" as any,
//     parentId: row.id ? row.id : 0,
//     code: "",
//     companyId: 1,
//     name: "",
//     email: "",
//     telphone: "",
//     vieworder: 100
//   };
//   department.selectRow = null;
//   department.showEdit = true;
// };

// 表单提交
const submitEvent = async () => {
  const $table = xTable.value;
  const $form = xForm.value;
  const errMap = await $form.validate();
  if (!errMap) {
    department.submitLoading = true;
    department.formData.bindTeamId =
      department.formData.bindTeamId == "" ? 0 : department.formData.bindTeamId;
    if (department.selectRow) {
      // 修改
      updateDepartment(department.formData).then((res: any) => {
        if (res.code === 0) {
          findList();
          addClose();
          Object.assign(department.selectRow, department.formData);
          successMessage("保存成功");
        } else {
          errorMessage(res.message);
          department.formData.bindTeamId == 0
            ? ""
            : department.formData.bindTeamId;
        }
        department.submitLoading = false;
      });
    } else {
      // 新增
      addDepartment(department.formData).then((res: any) => {
        if (res.code === 0) {
          findList();
          addClose();
          successMessage("新增成功");
        } else {
          errorMessage(res.message);
          department.formData.bindTeamId == 0
            ? ""
            : department.formData.bindTeamId;
        }
        department.submitLoading = false;
      });
    }
  }
};

const addClose = () => {
  nextTick(() => {
    department.showEdit = false;
    department.selectRow = null;
    department.submitLoading = false;
  });
};

// 修改权限
const dialog = reactive({
  showEdit: false,
  editPermissionLoading: false,
  tableData: [] as any[],
  menuIds: [] as any[],
  userIds: [] as any[],
  checkKey: [] as any[],
  defaultProps: {
    children: "nextMenuTreeDtos",
    label: (data, node) => {
      var cellValue = data.menutype === 0 ? "菜单" : "按钮";
      return data.menuname + "(" + cellValue + ")";
    },
    class: (data, node) => {
      return data.menutype === 0 ? "menuClass" : "btnClass";
    },
    value: "id",
    disabled: "false"
  }
});

// 获取选中的数据并渲染
const menuTree = ref<InstanceType<typeof ElTree>>();
const editPermissions = (id: any) => {
  dialog.showEdit = true;
  dialog.userIds = id;
  queryMenuRoleByRoleId(id).then((res: any) => {
    if (res.code === 0) {
      dialog.checkKey = res.data.map(function (item) {
        return item.menuId;
      });
      menuTree.value.setCheckedKeys([], true);
    }
  });
};
const nodeCheck = (data, obj) => {
  let isSelected = obj.checkedKeys.includes(data.id);
  let curNode = menuTree.value.getNode(data.id);
  let nodes = curNode.childNodes || [];
  setNodes(nodes, isSelected);
  if (isSelected) {
    let keys = getParentKey(curNode.parent);
    keys.forEach(item => {
      menuTree.value.setChecked(item, true, false);
    });
  }
};
const setNodes = (list = [], flag = false) => {
  if (!list.length) return [];
  for (let item of list) {
    item.checked = flag;
    if (item.childNodes && item.childNodes.length)
      setNodes(item.childNodes, flag);
  }
};
const getParentKey = (node, ret = []) => {
  node.key && ret.push(node.key);
  if (node.parent) getParentKey(node.parent, ret);
  return ret;
};
// 获取所有菜单
const getMenuTree = () => {
  queryMenutreeNoPermission().then((res: any) => {
    if (res.code === 0) {
      dialog.tableData = res.data;
    }
  });
};
// 权限分配表单提交
const insertMenuRole = async () => {
  dialog.editPermissionLoading = true;
  dialog.menuIds = [
    ...menuTree.value.getCheckedKeys(false),
    ...menuTree.value.getHalfCheckedNodes()
  ];
  var data = {
    ids: dialog.menuIds,
    id: dialog.userIds
  };
  addOrUpdateDeptMenu(data).then((res: any) => {
    if (res.code === 0) {
      handleClose();
      findList();
      successMessage("分配成功");
    } else {
      errorMessage(res.message);
    }
    dialog.editPermissionLoading = false;
  });
};

const handleClose = () => {
  nextTick(() => {
    menuTree.value.setCheckedKeys([], true);
    dialog.showEdit = false;
  });
};
// 获取所有班组
const getTeam = () => {
  queryTeamAll().then((res: any) => {
    if (res.code === 0) {
      department.teamData = res.data;
    }
  });
};
// mounted
onMounted(() => {
  nextTick(() => {
    findList();
    getMenuTree();
    getTeam();
    table.tableHeight = changeHeight();
  });
});
</script>

<template>
  <div>
    <!-- 工具栏 -->
    <vxe-form :data="table.listQuery">
      <vxe-form-item title="编码" field="code">
        <template #default="{ data }">
          <vxe-input v-model="data.code" placeholder="请输入编码"></vxe-input>
        </template>
      </vxe-form-item>
      <vxe-form-item title="名称" field="name">
        <template #default="{ data }">
          <vxe-input v-model="data.name" placeholder="请输入名称"></vxe-input>
        </template>
      </vxe-form-item>
      <vxe-form-item title="办公电话" field="telphone">
        <template #default="{ data }">
          <vxe-input
            v-model="data.telphone"
            placeholder="请输入办公电话"
          ></vxe-input>
        </template>
      </vxe-form-item>
      <vxe-form-item field="bindTeamId" title="关联班组">
        <template #default="{ data }">
          <el-select
            v-model="data.bindTeamId"
            filterable
            clearable
            size="small"
            placeholder="请选择关联班组"
            style="width: 100%"
          >
            <el-option
              v-for="item in department.teamData"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </template>
      </vxe-form-item>
      <vxe-form-item>
        <template #default>
          <vxe-button
            icon="fa fa-search"
            status="primary"
            @click="findList"
            v-auth="routeName + ':search'"
            >查询</vxe-button
          >
          <!-- <vxe-button
            icon="fa fa-plus"
            status="primary"
            @click="insertEvent"
            v-auth="routeName + ':add'"
            >新增</vxe-button
          > -->
        </template>
      </vxe-form-item>
    </vxe-form>
    <!-- 列表 -->
    <vxe-table
      resizable
      show-header-overflow
      show-overflow
      keep-source
      ref="xTable"
      row-id="u9Id"
      :row-config="{ isCurrent: true, isHover: true }"
      :print-config="{}"
      :export-config="{}"
      :loading="table.loading"
      :tree-config="department.treeConfig"
      :edit-config="{ trigger: 'click', mode: 'row', showStatus: true }"
      :height="table.tableHeight"
      :data="table.tableData"
    >
      <vxe-column
        field="name"
        title="部门名称"
        tree-node
        min-width="300"
        type="html"
      >
      </vxe-column>
      <vxe-column field="code" title="部门编码" min-width="120"></vxe-column>
      <vxe-column
        field="telphone"
        title="办公电话"
        min-width="120"
      ></vxe-column>
      <vxe-column field="email" title="邮箱" min-width="200"></vxe-column>
      <vxe-column
        field="bindTeamName"
        title="关联班组"
        min-width="100"
      ></vxe-column>
      <vxe-column title="操作" width="220" fixed="right">
        <template #default="{ row }">
          <!-- <vxe-button
            type="text"
            icon="fa fa-plus"
            @click="insertEvent(row)"
            v-auth="'department:add'"
            >新增子部门</vxe-button
          > -->
          <vxe-button
            type="text"
            icon="fa fa-link"
            @click="editEvent(row)"
            v-auth="'department:edit'"
            >关联班组</vxe-button
          >
          <!-- <vxe-button
            type="text"
            icon="fa fa-trash-o"
            @click="removeEvent(row)"
            v-auth="'department:delete'"
            >删除</vxe-button
          > -->
          <vxe-button
            type="text"
            icon="fa fa-edit"
            v-auth="routeName + ':editP'"
            @click="editPermissions(row.id)"
            >编辑权限</vxe-button
          >
        </template>
      </vxe-column>
    </vxe-table>
    <!-- 表单弹框 -->
    <vxe-modal
      v-model="department.showEdit"
      :title="department.selectRow ? '编辑&保存' : '新增&保存'"
      width="400"
      min-width="400"
      min-height="300"
      :loading="department.submitLoading"
      resize
      showFooter
      destroy-on-close
      @close="addClose"
    >
      <template #default>
        <vxe-form
          ref="xForm"
          :data="department.formData"
          :rules="department.formRules"
          title-align="right"
          title-width="100"
        >
          <vxe-form-item field="code" title="部门编码" :span="24">
            <template #default="{ data }">
              <vxe-input
                v-model="data.code"
                :clearable="false"
                placeholder="请输入部门编码"
                :readonly="department.selectRow ? true : false"
              ></vxe-input>
            </template>
          </vxe-form-item>
          <vxe-form-item field="name" title="部门名称" :span="24">
            <template #default="{ data }">
              <vxe-input
                v-model="data.name"
                :clearable="false"
                placeholder="请输入部门名称"
                :readonly="department.selectRow ? true : false"
              ></vxe-input>
            </template>
          </vxe-form-item>
          <vxe-form-item field="email" title="邮箱" :span="24">
            <template #default="{ data }">
              <vxe-input
                v-model="data.email"
                :clearable="false"
                placeholder="请输入邮箱"
                :readonly="department.selectRow ? true : false"
              ></vxe-input>
            </template>
          </vxe-form-item>
          <vxe-form-item field="telphone" title="办公电话" :span="24">
            <template #default="{ data }">
              <vxe-input
                v-model="data.telphone"
                :clearable="false"
                placeholder="请输入办公电话"
                :readonly="department.selectRow ? true : false"
              ></vxe-input>
            </template>
          </vxe-form-item>
          <vxe-form-item field="bindTeamId" title="关联班组" :span="24">
            <template #default="{ data }">
              <el-select
                v-model="data.bindTeamId"
                filterable
                size="small"
                placeholder="请选择关联班组"
                style="width: 100%"
              >
                <el-option
                  v-for="item in department.teamData"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </template>
          </vxe-form-item>
        </vxe-form>
      </template>
      <template #footer>
        <vxe-button @click="addClose">取 消</vxe-button>
        <vxe-button status="primary" @click="submitEvent">确 定</vxe-button>
      </template>
    </vxe-modal>
    <!-- 表单弹框 -->
    <el-dialog
      title="编辑权限"
      v-model="dialog.showEdit"
      v-if="dialog.showEdit"
      width="400px"
      top="7vh"
      :before-close="handleClose"
      :close-on-click-modal="false"
    >
      <el-tree
        :data="dialog.tableData"
        show-checkbox
        default-expand-all
        node-key="id"
        ref="menuTree"
        :check-strictly="true"
        :default-checked-keys="dialog.checkKey"
        :props="dialog.defaultProps"
        @check="nodeCheck"
      ></el-tree>
      <!-- 
         -->
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleClose" size="small">取 消</el-button>
          <el-button
            type="primary"
            @click="insertMenuRole"
            size="small"
            :loading="dialog.editPermissionLoading"
            >确 定</el-button
          >
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<style scoped>
@import url("/@/style/dialog.css");
</style>
<style>
.keyword-lighten {
  color: #000;
  background-color: #ffff00;
}
</style>
<style lang="scss" scoped>
.vxe-input + .vxe-button,
.vxe-input + .vxe-button--dropdown,
.vxe-button + .vxe-button,
.vxe-button + .vxe-button--dropdown {
  margin-left: 0;
}

// .vxe-button.type--button:not(.is--round) {
//   border-radius: 0;
// }

.vxe-toolbar.size--medium {
  padding: 10px;
}

.vxe-table--render-default.size--medium {
  margin-top: 12px;
}

.vxe-button.size--medium.type--button {
  margin-left: 1em;
  height: 32px;
}

.text-model {
  &:hover {
    cursor: pointer;
  }
}
</style>
